package tools

import (
	"context"
	"encoding/json"
	"fmt"

	"gitee.com/EagleMao/eino_n9e_tool/pkg/logger"
	"github.com/cloudwego/eino/components/tool"
	"github.com/cloudwego/eino/schema"
)

func GetQueryCurrentEventTool(backService *N9EService) tool.InvokableTool {
	return &ToolQueryCurrentEvent{
		backService: backService,
	}
}

// ToolQueryCurrentEvent 查询当前告警事件工具
type ToolQueryCurrentEvent struct {
	backService *N9EService
}

type CurrentEventParam struct {
	// 业务组id
	Bgid *int64 `json:"bgid,omitempty"`
	// 数据源参数
	DatasourceIDS *string `json:"datasource_ids,omitempty"`
	// 结束时间
	Etime *string `json:"etime,omitempty"`
	// 事件ids，多个用逗号分隔
	EventIDS *string `json:"event_ids,omitempty"`
	// 时间跨度
	Hours *string `json:"hours,omitempty"`
	Limit *string `json:"limit,omitempty"`
	// 是否仅查看我所属的业务组告警
	MyGroups *bool   `json:"my_groups,omitempty"`
	P        *string `json:"p,omitempty"`
	Prods    *string `json:"prods,omitempty"`
	// ruleId
	Rid *string `json:"rid,omitempty"`
	// 起始时间
	Stime *string `json:"stime,omitempty"`
}

func (t *ToolQueryCurrentEvent) Info(ctx context.Context) (*schema.ToolInfo, error) {
	toolInfo := &schema.ToolInfo{
		Name: "query_current_event",
		Desc: "获取夜莺告警事件列表,可以查询当前活跃的告警",
		ParamsOneOf: schema.NewParamsOneOfByParams(
			map[string]*schema.ParameterInfo{
				"bgid": {
					Type:     schema.Integer,
					Desc:     "业务组id",
					Required: false,
				},
				"datasource_ids": {
					Type:     schema.String,
					Desc:     "数据源参数",
					Required: false,
				},
				"etime": {
					Type:     schema.String,
					Desc:     "结束时间",
					Required: false,
				},
				"event_ids": {
					Type:     schema.String,
					Desc:     "事件ids，多个用逗号分隔",
					Required: false,
				},
				"hours": {
					Type:     schema.String,
					Desc:     "时间跨度",
					Required: false,
				},
				"limit": {
					Type:     schema.String,
					Desc:     "分页大小",
					Required: false,
				},
				"my_groups": {
					Type:     schema.Boolean,
					Desc:     "是否仅查看我所属的业务组告警",
					Required: false,
				},
				"p": {
					Type:     schema.String,
					Desc:     "分页页码",
					Required: false,
				},
				"prods": {
					Type:     schema.String,
					Desc:     "产品线",
					Required: false,
				},
				"rid": {
					Type:     schema.String,
					Desc:     "ruleId",
					Required: false,
				},
				"stime": {
					Type:     schema.String,
					Desc:     "起始时间",
					Required: false,
				},
			}),
	}
	return toolInfo, nil
}

func (t *ToolQueryCurrentEvent) InvokableRun(ctx context.Context, argumentsInJSON string, opts ...tool.Option) (string, error) {
	p := &CurrentEventParam{}
	logger.Info(fmt.Sprintf("当前查询参数: %v", argumentsInJSON))
	if err := json.Unmarshal([]byte(argumentsInJSON), p); err != nil {
		return "", err
	}
	resp, err := t.backService.GetCurrentEvent(*p)

	if err != nil {
		return "", err

	}

	res, err := json.Marshal(resp)

	if err != nil {
		logger.Info(fmt.Sprintf("%v 序列号失败 %v", resp, err))
		return "", err
	}

	return string(res), err
}
